package search;

import act.End;
import act.IActor;
import act.IReceiver;

/**
 * Class to distribute messages equally to different targets.
 * @author poconnor
 */
public class Distributor implements IReceiver{

	private final IActor[] targets;
	
	private int currentIndex = 0;

	private IActor actor;
	
	public Distributor(IActor[] targets)
	{
		this.targets = targets;
	}
	
	
	@Override
	public void receive(Object msg) {

		if(msg instanceof End)
		{
			this.actor.stop();
			//send End message on to all targets so that they can terminate in their own time
			for(IActor target: targets)
			{
				target.send(msg);
			}				
			return;
		}
		else
		{
			//distribute messages equally to all targets
			currentIndex++;
			if(currentIndex >= targets.length)
			{
				currentIndex = 0;
			}
			if(targets.length != 0)
			{
				targets[currentIndex].send(msg);
			}
		}
	}

	@Override
	public void setActor(IActor actor) {
		this.actor = actor;
	}

	
	
}
